package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.domain.vo.DeptVO;
import com.ruoyi.li.work.domain.vo.SysDeptSchoolVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.li.work.service.ISysDeptService;

/**
 * 学校信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
@Api(tags = "school-学校")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;


    /**
     * 获取学校列表
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询学校列表 树状", notes = "查询学校列表 树状")
    public TableDataInfo list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptListVO(dept);
        return getDataTable(depts);
    }

    /**
     * 获取平面学校列表
     */
    @GetMapping("/depts")
    public AjaxResult depts() {
        return deptService.selectDepts();
    }

    /**
     * 获取学校列表
     */
    @GetMapping("/school")
    @ApiOperation(value = "获取学校列表", notes = "获取学校列表")
    public AjaxResult deptSchool() {
        return deptService.deptSchool();
    }

    /**
     * 获取企业列表
     */
    @GetMapping("/enterprise")
    @ApiOperation(value = "获取企业列表", notes = "获取企业列表")
    public AjaxResult deptEnterprise() {
        return deptService.deptEnterprise();
    }

    /**
     * 查询班级列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据学校编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }


    /**
     * 新增学校//注册
     */
    @PostMapping("/addSchool")
    @ApiOperation("新增学校/注册")
    public AjaxResult addSchool(@RequestBody List<SysDeptSchoolVO> depts) {
        System.out.println(depts);
        for (SysDeptSchoolVO dept : depts) {
            // 检查列表中是否有重复的 deptName
            List<SysDept> selectName = deptService.selectName(dept.getDeptName());
            if (selectName.size() > 0) {
                String dn = "名称'" + dept.getDeptName() + " 重复，添加失败";
                return error(dn);
            }
        }
        return deptService.addSchool(depts);
    }

    /**
     * 新增学校//后台
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "学校管理", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增学校/后台")
    public AjaxResult add(@Validated @RequestBody List<SysDept> depts) {
        String dn = "1";
        Set<String> deptNameSet = new HashSet<>();
        for (SysDept dept : depts) {
            // 检查列表中是否有重复的 deptName
            if (!deptNameSet.add(dept.getDeptName())) {
                dn = "名称'" + dept.getDeptName() + " 重复，上传失败";
                break;
            }
            if (null == dept.getDeptName() || dept.getDeptName().equals("")) {
                dn = "有未输入的名称，新增失败";
                break;
            }
            if (dept.getDeptName().length() > 20) {
                dn = "新增'" + dept.getDeptName() + "'失败，名称长度不能超过10个字";
                break;
            }
            if (deptService.checkDeptNameUnique(dept)) {
                dn =  dept.getDeptName() + "'失败，当前名称已存在";
                break;
            }
            dept.setCreateBy(getUsername());
        }
        if (!dn.equals("1")) {
            return error(dn);
        }
        return deptService.insertDept(depts);
    }

    /**
     * 修改学校
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "学校管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (deptService.checkDeptNameUnique(dept)) {
            return error("学校班级'" + dept.getDeptName() + "'失败，学校名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return error("学校班级'" + dept.getDeptName() + "'失败，上级学校不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return error("该学校包含未停用的子学校！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除学校
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "学校管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptIds}")
    public AjaxResult remove(@PathVariable Long[] deptIds)
    {
        for (Long deptId : deptIds) {
            if (deptService.hasChildByDeptId(deptId))
            {
                return warn("存在下级,不允许删除");
            }
            if (deptService.checkDeptExistUser(deptId))
            {
                return warn("已分配,不允许删除");
            }
            deptService.checkDeptDataScope(deptId);
        }

        return deptService.deleteDeptById(deptIds);
    }
}
